﻿/*
This file is part of Claymore.
Copyright (C) 2010, Fabrice Michellonet (fabrice dot michellonet at gmail dot com)

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

using System;
using System.Reflection;

namespace Claymore
{
    public partial class ClaymorePresenterManager
    {

        /// <summary>
        /// Creates a presenter based on the implemented View interface it controls.
        /// </summary>
        /// <typeparam name="TIView">The type of the view interface.</typeparam>
        /// <param name="view"></param>
        /// <returns></returns>
        public virtual IPresenter<TIView> CreatePresenterFor<TIView>(IView view) where TIView : class, IView
        {
            if(view == null)
                throw new ArgumentNullException("view", "Presenter is always initialized with the view it controls.");
            
            Type viewType = typeof (TIView);
            
            if(! _viewType2PresenterType.ContainsKey(viewType))
                return null;

            Type presenterType = _viewType2PresenterType[viewType];

            ConstructorInfo ctor = presenterType.GetConstructor(new [] { viewType });
            
            // ctor should never be null.
            IPresenter<TIView> presenter = (IPresenter<TIView>)ctor.Invoke(new object[] { view });

            if(!_viewType2IPresenter.ContainsKey(viewType))
                _viewType2IPresenter.Add(viewType, presenter);

            return presenter;
        }

    }
}
